package com.granada.behaviour.base;

import com.granada.service.RedisService;
import com.granada.utils.JwtTokenUtil;
import com.granada.constants.Constant;
import com.granada.exception.BusinessException;
import com.granada.exception.code.BaseResponseCode;
import com.granada.vo.req.LoginReqVO;
import com.granada.vo.resp.LoginRespVO;
import com.granada.vo.resp.UserLoginAppRespVO;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.TimeUnit;


public abstract class UserAuthBehavior implements com.granada.behaviour.interfaces.UserAuthBehavior {
    @Autowired
    public RedisService redisService;
    public abstract String refreshToken(String refreshToken, String accessToken) throws Exception;
    public abstract List<UserLoginAppRespVO> getUserLoginInfo(Long userId) throws Exception;

    public LoginRespVO login(LoginReqVO vo) throws Exception{ return null; }
    public abstract Boolean logging(LoginReqVO vo) throws Exception;

    public void logout(String accessToken,String refreshToken) throws Exception{
        if(StringUtils.isEmpty(accessToken)){
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        Subject subject = SecurityUtils.getSubject();
//        log.info("subject.getPrincipals()={}",subject.getPrincipals());
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        Long userId = JwtTokenUtil.getUserId(accessToken);

        redisService.set(Constant.JWT_REFRESH_TOKEN_BLACKLIST+accessToken,userId,JwtTokenUtil.getRemainingTime(accessToken), TimeUnit.MILLISECONDS);

        if(StringUtils.isNotBlank(refreshToken)) {
            redisService.set(Constant.JWT_REFRESH_TOKEN_BLACKLIST+refreshToken,userId,JwtTokenUtil.getRemainingTime(refreshToken),TimeUnit.MILLISECONDS);
        }
        redisService.delete(Constant.IDENTIFY_CACHE_KEY+userId);

    }

}
